#!/bin/bash
# K8s CronJob 部署脚本
# 用途：一键部署所有定时任务到K8s集群
# 执行位置：Master 节点的 /root/k8s/ 目录

set -euo pipefail

echo "========================================="
echo "  K8s CronJob 定时任务部署脚本"
echo "========================================="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查当前目录
if [ ! -f "namespace.yaml" ]; then
    echo -e "${RED}❌ 未找到 namespace.yaml，请确保在 /root/k8s/ 目录执行此脚本${NC}"
    echo "当前目录: $(pwd)"
    echo "请执行: cd /root/k8s && bash init-deploy.sh"
    exit 1
fi

# 检查kubectl
if ! command -v kubectl &> /dev/null; then
    echo -e "${RED}❌ kubectl 未安装或不在PATH中${NC}"
    exit 1
fi

# 检查集群连接
if ! kubectl cluster-info &> /dev/null; then
    echo -e "${RED}❌ 无法连接到K8s集群${NC}"
    exit 1
fi

echo -e "${GREEN}✅ kubectl 已连接到集群${NC}"
kubectl get nodes
echo ""

# 步骤1: 创建命名空间
echo "========== 步骤1: 创建命名空间 =========="
kubectl apply -f namespace.yaml
echo ""

# 步骤2: 创建RBAC
echo "========== 步骤2: 创建RBAC =========="
kubectl apply -f rbac.yaml
echo ""

# 步骤3: 创建Secrets
echo "========== 步骤3: 创建Secrets =========="
echo -e "${YELLOW}⚠️  请确保已在 secrets.yaml 中填写正确的密码${NC}"
kubectl apply -f secrets.yaml
echo ""

# 步骤4: 创建PVC
echo "========== 步骤4: 创建PVC =========="
kubectl apply -f pvc-logs.yaml
echo ""

# 等待PVC绑定
echo "等待PVC绑定..."
kubectl wait --for=condition=Bound pvc/task-logs-pvc -n tasks --timeout=60s || echo -e "${YELLOW}⚠️  PVC未立即绑定，将在首次使用时绑定${NC}"
echo ""

# 步骤5: 部署CronJob
echo "========== 步骤5: 部署CronJob =========="
kubectl apply -f cronjob-offline-monitor.yaml
kubectl apply -f cronjob-daily-tasks.yaml
echo ""

# 验证部署
echo "========== 部署验证 =========="
echo ""
echo "命名空间资源:"
kubectl get all -n tasks
echo ""

echo "CronJob列表:"
kubectl get cronjobs -n tasks
echo ""

echo "Secrets:"
kubectl get secrets -n tasks
echo ""

echo "PVC状态:"
kubectl get pvc -n tasks
echo ""

echo "========================================="
echo -e "${GREEN}✅ 部署完成！${NC}"
echo "========================================="
echo ""
echo "后续操作："
echo "1. 手动触发测试："
echo "   kubectl create job -n tasks offline-test-001 --from=cronjob/device-offline-monitor"
echo "   kubectl create job -n tasks daily-test-001 --from=cronjob/daily-tasks"
echo ""
echo "2. 查看日志："
echo "   kubectl logs -n tasks -l app=device-offline-monitor -f"
echo "   kubectl logs -n tasks -l app=daily-tasks -f"
echo ""
echo "3. 查看CronJob状态："
echo "   kubectl get cronjobs -n tasks -w"
echo ""
echo "4. 删除测试Job："
echo "   kubectl delete job -n tasks offline-test-001"
echo "   kubectl delete job -n tasks daily-test-001"
echo ""
